<template>
  <div style="height: 100%">
    <div class="flex_cm container" style="height: 100%">
      <search
        :form_data="header_list"
        @changeIsShow="
          (e) => {
            header_list[e].isShow = !header_list[e].isShow;
            header_list[e].value = '';
          }
        "
        @search="search_key"
        @reset="
          header_list.forEach((item) => {
            item.value = '';
          }),
            search_key()
        "
      ></search>
      <div class="flex flex1">
        <div class="left">
          <div>
            <div class="fs_16 fw">部门列表</div>
            <el-button
              type="primary"
              @click="
                reset_form(),
                  (add_form_data.parentId = default_menu_id),
                  (show_box = true)
              "
              v-if="has_role_list[0].has_role"
              >新增部门</el-button
            >
          </div>
          <div style="height: calc(100% - 63px); overflow-y: scroll; overflow-x: hidden">
            <el-menu
              class="el-menu-vertical-demo"
              size="small"
              unique-opened
              :default-active="default_menu_id"
              @select="select_menu"
              @open="handleOpen"
            >
              <Menu :menuList="menu_list" :default_menu_id="default_menu_id"></Menu>
            </el-menu>
          </div>
        </div>
        <div class="right" v-if="default_menu_id != ''">
          <div>
            <div>
              <div class="fs_16 fw">部门信息</div>
              <el-button type="primary" @click="edit" v-if="has_role_list[1].has_role"
                >编辑</el-button
              >
            </div>
            <div class="desc_box">
              <div class="flex">
                <div style="flex-shrink: 0" class="flex">
                  <svgBtn
                    icon="dept_1"
                    style="font-size: 16px; margin-right: 8px"
                  ></svgBtn>
                  部门名称：
                </div>
                <el-tooltip :content="depart_info?.name" placement="bottom">
                  <span class="text_over">{{ depart_info?.name }}</span>
                </el-tooltip>
              </div>
              <div class="flex">
                <div style="flex-shrink: 0" class="flex">
                  <svgBtn
                    icon="dept_2"
                    style="font-size: 16px; margin-right: 8px"
                  ></svgBtn
                  >上级部门：
                </div>
                <el-tooltip :content="depart_info?.parentName" placement="bottom">
                  <span class="text_over">{{ depart_info?.parentName }}</span>
                </el-tooltip>
              </div>
              <div class="flex">
                <div class="flex">
                  <svgBtn
                    icon="dept_3"
                    style="font-size: 16px; margin-right: 8px"
                  ></svgBtn
                  >部门主管：
                </div>
                {{ depart_info?.memberName }}
              </div>
              <div class="flex">
                <span class="flex"
                  ><svgBtn
                    icon="dept_4"
                    style="font-size: 16px; margin-right: 8px"
                  ></svgBtn
                  >排序：</span
                >{{ depart_info?.sort }}
              </div>
              <div class="flex">
                <span class="flex"
                  ><svgBtn
                    icon="dept_6"
                    style="font-size: 16px; margin-right: 8px"
                  ></svgBtn
                  >状态：</span
                ><span v-if="depart_info?.isEnable" class="c_3580eb">已启用</span>
                <span v-else class="c_666">已停用</span>
              </div>
            </div>
            <div class="flex" style="line-height: 40px; padding: 0 20px 10px 20px">
              <span style="flex-shrink: 0" class="flex"
                ><svgBtn icon="dept_5" style="font-size: 16px; margin-right: 8px"></svgBtn
                >备注：</span
              >
              <el-tooltip :content="depart_info?.remark" placement="bottom-start">
                <div
                  class="flex1"
                  style="white-space: nowrap; overflow-x: auto; margin: 0 30px 0 0"
                >
                  {{ depart_info?.remark }}
                </div>
              </el-tooltip>
            </div>
          </div>
          <div style="height: 10px; background-color: #f0f2f5"></div>
          <div>
            <div class="flex_js p_bottom20">
              <div class="fs_16 fw">部门成员</div>
              <div class="flex">
                <el-button type="primary" @click="show_add_member_box = true"
                  >添加成员</el-button
                >
                <setTable
                  :data="header_list_1"
                  :height_size="height_size"
                  @changeShowTable="
                    (e) => {
                      header_list_1[e].showTable = !header_list_1[e].showTable;
                    }
                  "
                  @resetTableSet="
                    () => {
                      header_list_1.forEach((item) => {
                        item.showTable = true;
                      });
                    }
                  "
                  @changeHeightSize="
                    (e) => {
                      height_size = e;
                    }
                  "
                ></setTable>
              </div>
            </div>
            <el-table
              style="text-align: center"
              :data="member_list"
              :max-height="max_height"
              border
              highlight-current-row
              v-loading="loading"
              :default-sort="{ prop: 'name', order: 'descending' }"
              :row-style="{
                height: height_size == 2 ? '50px' : '',
              }"
              :cell-style="{
                padding: height_size == 3 ? '0' : '',
              }"
            >
              <el-table-column
                label="用户名"
                prop="memberName"
                v-if="header_list_1[0].showTable"
              ></el-table-column>
              <el-table-column
                label="昵称"
                prop="memberNickName"
                v-if="header_list_1[1].showTable"
              ></el-table-column>
              <el-table-column label="角色" v-if="header_list_1[2].showTable">
                <template #default="scope: any">
                  <div v-if="scope.row.memberName == depart_info?.memberName">
                    部门主管
                  </div>
                  <div v-else>部门成员</div>
                </template>
              </el-table-column>
              <el-table-column label="操作">
                <template #default="scope: any">
                  <el-button @click="remove_member(scope)">移除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
        <div class="right" v-else>
          <img
            src="@/assets/img/no_more.png"
            style="width: 200px; margin: 100px auto 0 auto"
            alt=""
          />
          <div class="tc m_top10 c_999">暂无数据</div>
        </div>
      </div>
    </div>
    <el-drawer
      v-model="show_add_member_box"
      direction="rtl"
      :close-on-click-modal="false"
    >
      <template #title>
        <h4>添加成员</h4>
      </template>
      <template #default>
        <el-select v-model="add_memberId_list" multiple filterable>
          <el-option
            v-for="item in user_list"
            :key="item.memberId"
            :label="item.name"
            :value="item.memberId"
            :disabled="
              member_list.find((item1) => item1.memberId == item.memberId) != undefined
            "
          ></el-option>
        </el-select>
        <div class="tr m_top10">
          <el-button
            type="primary"
            :disabled="!add_memberId_list.length"
            @click="submit_add_member"
            >确定</el-button
          >
        </div>
      </template>
    </el-drawer>
    <el-drawer
      v-model="show_box"
      direction="rtl"
      size="50%"
      @close="resetForm(adddepartmentform)"
      :close-on-click-modal="false"
    >
      <template #title>
        <h4 v-if="add_form_data.id == ''">新增部门</h4>
        <h4 v-else>编辑部门</h4>
      </template>
      <template #default>
        <el-form
          :model="add_form_data"
          :rules="rules"
          ref="adddepartmentform"
          label-width="100px"
        >
          <el-form-item label="部门名称" prop="name">
            <el-input
              v-model="add_form_data.name"
              placeholder="请输入"
              show-word-limit
              maxlength="30"
            ></el-input>
          </el-form-item>
          <el-form-item label="上级部门">
            <el-cascader
              clearable
              v-model="add_form_data.parentId"
              :options="add_form_data.id == '' ? add_form_data_menu_list : menu_list"
              :props="props"
            />
          </el-form-item>
          <el-form-item label="部门主管">
            <el-select v-model="add_form_data.memberId" clearable filterable>
              <el-option
                v-for="item in user_list"
                :key="item.memberId"
                :label="item.name"
                :value="item.memberId"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="主管并入部门" v-if="add_form_data.memberId != ''">
            <el-switch
              v-model="add_form_data.isCreate"
              active-text="是"
              inactive-text="否"
              inline-prompt
            />
          </el-form-item>
          <el-form-item label="排序">
            <el-input
              v-model="add_form_data.sort"
              placeholder="请输入"
              show-word-limit
              maxlength="3"
            ></el-input>
          </el-form-item>
          <el-form-item label="状态">
            <el-radio
              v-model="add_form_data.isEnable"
              :disabled="add_form_data.id == ''"
              :label="true"
              >启用</el-radio
            >
            <el-radio
              v-model="add_form_data.isEnable"
              :disabled="add_form_data.id == ''"
              :label="false"
              >停用</el-radio
            >
          </el-form-item>
          <el-form-item label="备注">
            <el-input
              type="textarea"
              resize="none"
              v-model="add_form_data.remark"
              placeholder="请输入"
              show-word-limit
              maxlength="300"
            ></el-input>
          </el-form-item>
          <div class="m_top10 tr">
            <el-button @click="resetForm(adddepartmentform)">取消</el-button>
            <el-button
              type="primary"
              :loading="btn_loading"
              @click="submit(adddepartmentform)"
              >确定</el-button
            >
          </div>
        </el-form>
      </template>
    </el-drawer>
  </div>
</template>

<script lang="ts" setup>
import { check_role, handle_search_key } from "@/utils/check_role"; // 权限校验
import search from "@/view/components/search.vue";
import setTable from "@/view/components/setTable.vue";
import svgBtn from "@/components/svg_button.vue";
import Menu from "./menu.vue";
import { onMounted, ref, onUnmounted } from "vue";
import { FormInstance, ElMessage, ElMessageBox } from "element-plus";
import axios from "@/service/HttpRequest";
import serviceApi from "@/service/api";
import EventBus from "@/utils/EventBus";
import { useStore } from "vuex";

const has_role_list = ref([
  { path: "depart/post", has_role: false },
  { path: "depart/put", has_role: false },
]);
const store = useStore();
const props = ref({ checkStrictly: true });
const adddepartmentform = ref<FormInstance>();
const rules = ref({
  name: [{ required: true, message: "请输入部门名称", trigger: "blur" }],
});
const header_list = ref([
  {
    label: "部门名称",
    value: "",
    showTable: true,
    type: "input",
    isShow: true,
    options: [],
  },
  {
    label: "上级部门",
    value: "",
    showTable: true,
    type: "input",
    isShow: true,
    options: [],
  },
  {
    label: "状态",
    value: "",
    showTable: true,
    type: "select",
    isShow: false,
    options: [
      { value: "1", label: "已启用" },
      { value: "0", label: "已停用" },
    ],
  },
  {
    label: "部门主管",
    value: "",
    showTable: true,
    type: "input",
    isShow: false,
    options: [],
  },
  {
    label: "备注",
    value: "",
    showTable: true,
    type: "input",
    isShow: false,
    options: [],
  },
]);
const header_list_1 = ref([
  {
    label: "用户名",
    value: "",
    showTable: true,
    type: "input",
    isShow: false,
    options: [],
  },
  {
    label: "昵称",
    value: "",
    showTable: true,
    type: "input",
    isShow: false,
    options: [],
  },
  {
    label: "角色",
    value: "",
    showTable: true,
    type: "input",
    isShow: false,
    options: [],
  },
]);
const max_height = ref();
const height_size = ref(1);
const menu_list = ref(); // 左侧列表使用
// const select_list = ref(); // 下拉选择框使用
const default_menu_id = ref("");
const page_data = ref({
  enterpriseId: store.state.enterprise_id,
  isEnable: "",
  name: "",
  superiorDept: "",
  director: "",
  remark: "",
});
const add_form_data = ref({
  id: "",
  name: "",
  parentId: "",
  parentName: "",
  memberName: "",
  memberId: "",
  sort: "",
  isEnable: true,
  remark: "",
  isCreate: false,
  enterpriseId: store.state.enterprise_id,
});
const member_list = ref([]);
const member_page_data = ref({
  current: 1,
  pageSize: 1000,
  enterpriseId: store.state.enterprise_id,
  deptName: "",
  status: 2,
  name: "",
  nickName: "",
  wechat: "",
  phone: "",
  roleName: "",
  remark: "",
});
const loading = ref(false);
const show_box = ref(false);
const handleOpen = (key: string) => {
  console.log(key);
  default_menu_id.value = key;
  get_depart_info();
  select_list_disabled(key, menu_list.value);
};
const show_add_member_box = ref(false);
const add_memberId_list = ref([]);
const submit_add_member = () => {
  axios
    .request({
      url: serviceApi.depart_user_add,
      method: "post",
      data: {
        deptId: default_menu_id.value,
        memberIds: add_memberId_list.value,
      },
    })
    .then(() => {
      ElMessage.success("操作成功！");
      setTimeout(() => {
        get_depart_info();
      }, 1000);
      show_add_member_box.value = false;
      add_memberId_list.value = [];
    })
    .catch((err) => {
      ElMessage.error(err);
    });
};
const remove_member = (e) => {
  console.log(e);
  ElMessageBox.confirm("确定将该成员移除部门", "", {
    cancelButtonText: "取消",
    confirmButtonText: "确定",
    closeOnClickModal: false,
    type: "warning",
  })
    .then(() => {
      remove_axios(e.row.memberId);
    })
    .catch(() => {});
};
const remove_axios = (e) => {
  axios
    .request({
      url: serviceApi.depart_user_remove,
      method: "delete",
      params: {
        deptId: default_menu_id.value,
        enterMemberId: e,
      },
    })
    .then(() => {
      ElMessage.success("操作成功！");
      setTimeout(() => {
        get_list();
      }, 1000);
    })
    .catch((err) => {
      ElMessage.error(err);
    });
};
onMounted(() => {
  max_height.value = window.innerHeight - 446; // 带分页的 table 高度
  has_role_list.value.forEach((item) => {
    item.has_role = check_role(item);
  });
  EventBus.on("refresh", () => {
    // get_list()
    get_user_list();
    ElMessage.success("刷新成功！");
  });
  get_list();
  get_user_list();
});
onUnmounted(() => {
  EventBus.off("refresh");
});
const edit = () => {
  console.log(add_form_data.value, depart_info.value);
  add_form_data.value = JSON.parse(JSON.stringify(depart_info.value));
  show_box.value = true;
};
const btn_loading = ref(false);
const submit = async (formEl: FormInstance | undefined) => {
  if (btn_loading.value) return;
  btn_loading.value = true;
  await formEl.validate((valid) => {
    if (valid) {
      console.log(add_form_data.value);
      add_form_data.value.parentId = Array.isArray(add_form_data.value.parentId)
        ? add_form_data.value.parentId.at(-1)
        : add_form_data.value.parentId;
      axios
        .request({
          url:
            add_form_data.value.id == ""
              ? serviceApi.depart_crud
              : serviceApi.depart_crud + "/" + add_form_data.value.id,
          method: add_form_data.value.id == "" ? "post" : "put",
          data: add_form_data.value,
        })
        .then(() => {
          ElMessage.success("操作成功！");
          setTimeout(() => {
            show_box.value = false;
            btn_loading.value = false;
            // 编辑没有主管  原主管移除
            if (add_form_data.value.memberId == "" && depart_loader_id.value != "") {
              remove_axios(depart_loader_id.value);
            }
            // 编辑有主管 没 并入部门 此主管移除
            if (add_form_data.value.memberId != "" && !add_form_data.value.isCreate) {
              remove_axios(add_form_data.value.memberId);
            }
            get_list();
          }, 1000);
        })
        .catch((err) => {
          btn_loading.value = false;
          ElMessage.error(err);
        });
    } else {
      btn_loading.value = false;
    }
  });
};
const add_form_data_menu_list = ref([]);
const get_list = () => {
  axios
    .request({
      url: serviceApi.depart_list,
      method: "post",
      data: handle_search_key(page_data.value),
    })
    .then((res) => {
      if (res.data.length) {
        res.data.forEach((item) => {
          if (item.parentId == "-1") {
            if (default_menu_id.value == item.id) {
              get_depart_info();
            }
          }
        });
        menu_list.value = arrToTree(
          res.data.sort(function (a, b) {
            return a.sort - b.sort;
          })
        );
        add_form_data_menu_list.value = JSON.parse(JSON.stringify(menu_list.value));
        default_menu_id.value =
          default_menu_id.value == "" ? menu_list.value[0].id : default_menu_id.value;
        get_depart_info();
        console.log(menu_list.value);
      } else {
        menu_list.value = [];
        default_menu_id.value = "";
      }
    });
};
const depart_info = ref();
const depart_loader_id = ref();
const get_depart_info = () => {
  axios
    .request({
      url: serviceApi.depart_crud + "/" + default_menu_id.value,
      method: "get",
    })
    .then((res) => {
      console.log(res);
      member_page_data.value.deptName = res.data.name;
      depart_loader_id.value = res.data.member.id == "-1" ? "" : res.data.member.id;
      select_list_disabled(res.data.id, menu_list.value);
      add_form_data.value = {
        isCreate: res.data.isCreate,
        id: res.data.id,
        parentName: res.data.parentDept.name,
        memberName: res.data.member.name,
        name: res.data.name,
        parentId: res.data.parentDept.id,
        memberId: res.data.member.id == "-1" ? "" : res.data.member.id,
        sort: res.data.sort,
        isEnable: res.data.isEnable,
        remark: res.data.remark,
        enterpriseId: store.state.enterprise_id,
      };
      depart_info.value = JSON.parse(JSON.stringify(add_form_data.value));
      get_member_list();
    });
};
// 级联选择 禁用自身
const select_list_disabled = (e, arr, flag?) => {
  arr.forEach((i) => {
    if (i.id == e) {
      i.disabled = true;
      if (i.children) {
        // 下级不可选
        select_list_disabled(e, i.children, true);
      }
    } else {
      if (flag) {
        i.disabled = true;
        if (i.children) {
          // 下级不可选
          select_list_disabled(e, i.children, true);
        }
      } else {
        i.disabled = false;
        if (i.children) {
          select_list_disabled(e, i.children);
        }
      }
    }
  });
};
const user_list = ref();
const get_user_list = () => {
  loading.value = true;
  let data = {
    current: 1,
    pageSize: 10000,
    enterpriseId: store.state.enterprise_id,
    deptName: "",
    status: 2,
    name: "",
    nickName: "",
    wechat: "",
    phone: "",
    roleName: "",
    remark: "",
  };
  axios
    .request({
      url: serviceApi.user_list,
      method: "post",
      data: handle_search_key(data),
    })
    .then((res) => {
      console.log(res);
      user_list.value = res.data.content;
      loading.value = false;
    })
    .catch((err) => {
      ElMessage.error(err);
      loading.value = false;
    });
};
const select_menu = (e) => {
  default_menu_id.value = e;
  select_list_disabled(e, menu_list.value);
  get_depart_info();
};

const get_member_list = () => {
  axios
    .request({
      url: serviceApi.depart_user_list,
      method: "post",
      params: { deptId: default_menu_id.value },
    })
    .then((res) => {
      console.log(res);
      member_list.value = res.data === null ? [] : res.data;
      //   member_total.value = parseInt(res.data.totalElements);
      loading.value = false;
    })
    .catch((err) => {
      loading.value = false;
      ElMessage.error(err);
    });
};
// let list_debounce = debounce(200, get_member_list);
const search_key = () => {
  console.log(header_list.value);
  page_data.value = {
    enterpriseId: store.state.enterprise_id,
    isEnable: header_list.value[2].value,
    name: header_list.value[0].value,
    superiorDept: header_list.value[1].value,
    director: header_list.value[3].value,
    remark: header_list.value[4].value,
  };
  default_menu_id.value = "";
  select_list_disabled("", menu_list.value);
  get_list();
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  reset_form();
  show_box.value = false;
};
const reset_form = () => {
  add_form_data.value = {
    parentName: "",
    memberName: "",
    id: "",
    name: "",
    parentId: "",
    memberId: "",
    sort: "",
    isEnable: true,
    remark: "",
    enterpriseId: store.state.enterprise_id,
    isCreate: false,
  };
};
const arrToTree = (list) => {
  var map = {};
  var result = [];
  list.forEach((item) => {
    map[item.id] = item;
  });
  list.forEach((item) => {
    item.label = item.name;
    item.value = item.id;
    let parent = map[item.parentId];
    if (parent) {
      if (!parent.children) {
        parent.children = [];
      }
      parent.children.push(item);
    } else {
      result.push(item);
    }
  });
  return result;
};
</script>

<style lang="scss" scoped>
:deep(.el-menu) {
  .el-sub-menu__title {
    background-color: #fff;
    &:hover {
      background-color: #fff;
    }
  }
  --el-menu-text-color: #333;
  --el-menu-hover-text-color: #333;
  --el-menu-bg-color: #fff;
  --el-menu-hover-bg-color: #fff;
}
:deep(.el-sub-menu.is-opened > .el-sub-menu__title) {
  color: #333;
}
:deep(.el-menu-item.is-active) {
  color: #3580eb;
}
.left {
  width: 300px;
  height: 100%;
  background-color: #fff;
  > div:first-child {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 15px 20px;
    border-bottom: 1px solid #d8d8d8;
  }
}
.right {
  flex: 1;
  width: calc(100% - 320px);
  height: 100%;
  display: flex;
  flex-direction: column;
  margin-left: 10px;
  background-color: #fff;
  > div:first-child {
    > div:first-child {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 15px 20px;
      border-bottom: 1px solid #d8d8d8;
    }

    .desc_box {
      padding: 10px 20px 0 20px;
      line-height: 40px;
      display: flex;
      flex-wrap: wrap;
      > div {
        width: 20%;
      }
    }
    span:first-child {
      color: #999;
    }
  }
  > div:last-child {
    flex: 1;
    height: 100%;
    margin-top: 10px;
    background-color: #fff;
    padding: 0 20px;
    position: relative;
  }
}
</style>
